#include "Game.h"
#include "PrimitiveShape.h"

Game::Game(void)
{
	SDL_Init(SDL_INIT_EVERYTHING);
	screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE | SDL_OPENGL);
	Globals::get()->setIsRunning(true);
	Globals::get()->setCameraRotateSpeed(5.0f);
	Globals::get()->setCameraMoveSpeed(0.1f);

	camera = new Camera();

	init();
}

void Game::init()
{
	glClearColor(0.0, 0.0, 0.0, 1.0);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(45, 640.0/480.0, 1.0, 500.0);
	glMatrixMode(GL_MODELVIEW);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_TEXTURE_2D);

	camera->init(0.0f, 0.0f, 10.0f);

	skybox = new SkyBox(
		"D:\\Resources\\SkyBox1\\",
		"left.png", "back.png", "right.png",
		"front.png", "top.png", "bottom.png"
	);
}

void Game::drawAll()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();

	camera->rotate();
	skybox->draw(50.0f);
	camera->move();

	EntityManager::get()->drawAll();
}

void Game::run()
{
	while (Globals::get()->isRunning() == true)
	{
		time = SDL_GetTicks();
		while (SDL_PollEvent(&evt))
		{
			switch (evt.type)
			{
			case SDL_QUIT:
				Globals::get()->setIsRunning(false);
				break;
			case SDL_KEYDOWN:
				KeyManager::get()->injectKeyDown(evt.key.keysym.sym);
				break;
			case SDL_KEYUP:
				KeyManager::get()->injectKeyUp(evt.key.keysym.sym);
				break;
			}
		}

		drawAll();

		SDL_GL_SwapBuffers();
		if (1000/30 > (SDL_GetTicks() - time))
			SDL_Delay (1000/30 - (SDL_GetTicks() - time));
	}
}

Game::~Game(void)
{
}
